package uutalk.netcloud.talk.app;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.apkfuns.logutils.LogUtils;
import com.liulishuo.filedownloader.FileDownloader;

import java.util.UUID;

import uutalk.netcloud.talk.app.di.AppComponent;
import uutalk.netcloud.talk.app.di.DaggerAppComponent;
import uutalk.netcloud.talk.app.di.ThirdPartyManaer;
import uutalk.netcloud.talk.app.di.UtilsManager;
import uutalk.netcloud.talk.base.util.LanguageUtil;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;
import uutalk.netcloud.talk.base.di.AppModule;

/**
 * Created by hujie on 16/6/13.
 */
public class BootstrapApp extends Application {

    AppComponent appComponent;

    private static BootstrapApp app;

    @Override
    public void onCreate() {
        long i = System.currentTimeMillis();
        super.onCreate();
        app = this;
        LanguageUtil.init(app);
        appComponent = createAppComponent();
        initFileDownloader();
        initInject();
        LogUtils.d("app启动时间为%d毫秒", System.currentTimeMillis() - i);
    }

    /**
     * 初始化文件下载
     */
    private void initFileDownloader() {
        FileDownloader.setupOnApplicationOnCreate(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public String uuid() {

        String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(androidId)) {
            return androidId;
        }
        SharedPreferences spf = this.getSharedPreferences("uuid", Context.MODE_PRIVATE);
        if (spf.contains("uuid")) {
            String uuid = spf.getString("uuid", null);
            if (!TextUtils.isEmpty(uuid)) {
                return uuid;
            }
        }
        UUID uuid = UUID.randomUUID();
        String uniqueId = uuid.toString();
        spf.edit().putString("uuid", uniqueId).apply();

        return uniqueId;
    }

    /**
     *
     */
    private void initInject() {
        appComponent.inject(EventMamager.getInstance());
        appComponent.inject(ThirdPartyManaer.getInstance());
        appComponent.inject(UtilsManager.getInstance());
        UtilsManager.getInstance().initUtils();
        ThirdPartyManaer.getInstance().initThirdParty();
    }

    public static BootstrapApp get() {
        return app;
    }

    private AppComponent createAppComponent() {
        return DaggerAppComponent.builder().appModule(new AppModule(this)).build();
    }
    

    public AppComponent appComponent() {
        return appComponent;
    }

}
